package com.example.demo;


//import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.xdevapi.JsonArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonParser;
import com.sun.net.httpserver.HttpContext;
import net.sf.json.JSONArray;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.* ;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.example.demo.packageModel.emp;
import com.example.demo.packageModel.dept;
import com.example.demo.packageModel.Together;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.catalina.connector.Request;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import com.alibaba.fastjson.JSON;


@Controller
public class helloController {

    public int pages = -5;
    public int count = 5;
    public int Allcount = 0;
    String flag_del;
    String flag_update;
    String flag_insert;

    @Autowired  //与service层进行交互
    private service loginClService;


    @RequestMapping(value = "/db/{userId}")
    @ResponseBody
    public emp HuiXian(@PathVariable String userId) throws SQLException, ClassNotFoundException{
        return loginClService.Findemp(userId);
    }

    @RequestMapping(value = "/dball" , method = RequestMethod.POST)
    @ResponseBody
    public Collection<emp> Show_all() throws SQLException, ClassNotFoundException{
        //String name;
        //name = loginClService.Find(userId);
        //return name;
        System.out.println("Collector Show Info !!!");
        System.out.println(loginClService.Find_allemp());
        return loginClService.Find_allemp();
    }

    @RequestMapping(value = "/dbadd")
    @ResponseBody
    public void AddEmp() throws SQLException, ClassNotFoundException{
        emp user = new emp();
        user.setEmpno(8888);
        user.setEname("ZhangSan");
        user.setJob("HouQin");
        user.setMgr(666);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse("2020-07-23", df);
        user.setHiredate(date);
        BigDecimal bd0=new BigDecimal("6666.0");
        user.setSal(bd0);
        BigDecimal bd1=new BigDecimal("6666.0");
        user.setComm(bd1);
        user.setDeptno(20);
        loginClService.AddEmp(user);
    }

    @RequestMapping(value = "/dbdel")
    @ResponseBody
    public void DelEmp() throws SQLException, ClassNotFoundException{
        loginClService.DelEmp(7369);
    }

    @RequestMapping(value = "/dbcha")
    @ResponseBody
    public void Change() throws SQLException, ClassNotFoundException{
        emp user = new emp();
        user.setEmpno(7499);
        user.setEname("LiSi");
        user.setJob("HouQin");
        user.setMgr(666);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse("2020-07-23", df);
        user.setHiredate(date);
        BigDecimal bd0=new BigDecimal("6666.0");
        user.setSal(bd0);
        BigDecimal bd1=new BigDecimal("6666.0");
        user.setComm(bd1);
        user.setDeptno(20);
        loginClService.serChaEmp(user);
    }

    @RequestMapping(value = "/dbTo")
    @ResponseBody
    public Collection<Together> Show_To() throws SQLException, ClassNotFoundException{
        System.out.println(loginClService.GetAllInfo(pages, count).size());
        Iterator<Together> it = loginClService.GetAllInfo(pages, count).iterator();
        while(it.hasNext()){
            Together next = it.next();
            System.out.println(next.getJob()+" "+next.getEname());
        }
        return loginClService.GetAllInfo(pages,count);
    }
    @RequestMapping("/0")
    @ResponseBody
    public String Say(){
        return "index";
    }



    //end1.jsp
    @RequestMapping("/6")
    public ModelAndView moab(){
        ModelAndView model = new ModelAndView();
        model.setViewName("end1");
        return model;
    }



    //插入数据界面
    @RequestMapping("/insert")
    public ModelAndView insert(){
        ModelAndView model = new ModelAndView();
        model.setViewName("SQLinsert");
        return model;
    }

    //删除数据
    @RequestMapping("/del")
    public ModelAndView del(){
        ModelAndView model = new ModelAndView();
        model.setViewName("SQLdelete");
        return model;
    }

    //更改数据
    @RequestMapping("/update")
    public ModelAndView update(){
        ModelAndView model = new ModelAndView();
        model.setViewName("SQLupdate");
        return model;
    }


    //前端向后端传数据
    @RequestMapping(value = "/content")
    @ResponseBody
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ready to send!!");

        JSONObject lan1=new JSONObject();
        lan1.put("type", 111);
        lan1.put("timing", "40:20");
        lan1.put("time", "2016-06-23 13:44:40");
        lan1.put("price", "40.20");
        lan1.put("mainprice", "40.20");
        lan1.put("productname", "香薰SOD密 润肤奶膏身体乳");

        response.getWriter().println(lan1);
    }

    @RequestMapping("/trans")
    @ResponseBody
    public void readJSONStringFromRequestBody(HttpServletRequest request){
        System.out.println("Data Show!!!");
        //StringBuffer json = new StringBuffer();
        //JSONObject aaa = new JSONObject();
        String line = null;
        try{
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null){//一行一行的读数据

                int pa = Integer.parseInt( line );

                if (pa == -1){
                    if (pages <= 0)
                        pages = 0;
                    else
                        pages -= count;
                }
                else if (pa == -3) {
                    if((pages+count)<Allcount)
                        pages += count;
                }

                else {
                    pages = Integer.parseInt( line )*count;
                }

                System.out.println(pages);
            }
        }catch(Exception e){
            System.out.println("Error reading JSON String " + e.toString());
        }
    }

    //插入数据库操作
    @RequestMapping("/scanf")
    @ResponseBody
    public void japscanf(HttpServletRequest request)  throws SQLException, ClassNotFoundException{
        flag_insert = "";
        String line = null;
        String empno="";
        String empname="";
        String empjob="";
        String empmgr="NULL";
        String empdate="";
        String empsal="";
        String empcomm="NULL";
        String empdeptno="";

        try{
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null){//一行一行的读数据
                System.out.println(line);
                JSONObject jsonObject =  JSON.parseObject(line);
                empname = (String) jsonObject.get("name");
                empno = (String) jsonObject.get("empno");
                empjob = (String) jsonObject.get("job");
                empmgr = (String) jsonObject.get("mgr");
                empdate = (String) jsonObject.get("hiredate");
                empsal = (String) jsonObject.get("sal");
                empcomm = (String) jsonObject.get("comm");
                empdeptno = (String) jsonObject.get("deptno");
                //System.out.println(empno+"  "+empname);
            }
        }catch(Exception e){
            System.out.println("Error reading JSON String " + e.toString());
        }



        emp user = new emp();
        user.setEmpno(Integer.parseInt(empno));
        user.setEname(empname);
        user.setJob(empjob);
        Integer empMgr;
        if (empmgr.equals("NULL"))
            empMgr = null;
        else
            empMgr = Integer.parseInt( empmgr );
        user.setMgr(empMgr);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(empdate, df);
        user.setHiredate( date );
        BigDecimal bd0=new BigDecimal(empsal);
        user.setSal( bd0 );
        BigDecimal bd1;

        System.out.println(empcomm);

        if (empcomm.equals("NULL")){
            bd1 = null;
        }
        else {
            bd1= new BigDecimal(empcomm);
            }
        System.out.println("COMM: "+bd1);
        user.setComm( bd1 );
        user.setDeptno(Integer.parseInt( empdeptno ));

        boolean ee = loginClService.AddEmp(user);
        if(ee)
            flag_insert = "OK";
        else
            flag_insert = "NO";
        System.out.println("Control insert end!!!");

    }
    //插入是否成功，发到前端
    @RequestMapping("/insertflag")
    @ResponseBody
    public void japinsert(HttpServletRequest request, HttpServletResponse resp)  throws IOException{
        PrintWriter out=resp.getWriter();
        out.println(flag_insert);
        out.close();
    }

    //删除数据库操作
    @RequestMapping("/SQLdelete")
    @ResponseBody
    public void japdelete(HttpServletRequest request, HttpServletResponse resp)  throws SQLException, ClassNotFoundException, IOException{
        String line = null;
        String empno="";
        flag_del = "";

        try{
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null){//一行一行的读数据
                System.out.println(line);
                JSONObject jsonObject =  JSON.parseObject(line);
                empno = (String) jsonObject.get("empno");

                System.out.println("删除："+empno);
            }
        }catch(Exception e){
            System.out.println("Error reading JSON String " + e.toString());
        }


        boolean flag_dell = loginClService.DelEmp(Integer.parseInt(empno));
        if (flag_dell){
            PrintWriter out=resp.getWriter();
            flag_del = "OK";
            out.println(flag_del);
            out.close();
            System.out.println("Delete OK");
        }
        else{
            PrintWriter out=resp.getWriter();
            flag_del = "NO";
            out.println(flag_del);
            out.close();
            System.out.println("Delete NO");
        }

    }
    //删除是否成功，发到前端
    @RequestMapping("/SQLDEL")
    @ResponseBody
    public void delfalg(HttpServletRequest request, HttpServletResponse resp)  throws SQLException, ClassNotFoundException, IOException{
        PrintWriter out=resp.getWriter();
        out.println(flag_del);
        out.close();
    }


    //更新数据库
    @RequestMapping("/SQLupdate")
    @ResponseBody
    public void japupdate(HttpServletRequest request, HttpServletResponse resp)  throws SQLException, ClassNotFoundException, IOException{
        flag_update = "";
        String line = null;
        String empno="";
        String empname="";
        String empjob="";
        String empmgr="NULL";
        String empdate="";
        String empsal="";
        String empcomm="NULL";
        String empdeptno="";

        try{
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null){//一行一行的读数据
                System.out.println(line);
                JSONObject jsonObject =  JSON.parseObject(line);
                empname = (String) jsonObject.get("name");
                empno = (String) jsonObject.get("empno");
                empjob = (String) jsonObject.get("job");
                empmgr = (String) jsonObject.get("mgr");
                empdate = (String) jsonObject.get("hiredate");
                empsal = (String) jsonObject.get("sal");
                empcomm = (String) jsonObject.get("comm");
                empdeptno = (String) jsonObject.get("deptno");
                //System.out.println(empno+"  "+empname);
            }
        }catch(Exception e){
            System.out.println("Error reading JSON String " + e.toString());
        }



        if(loginClService.FindOK(Integer.parseInt( empno ))) {
            flag_update = "OK";
        }
        else {
            flag_update = "Not find in DB !!!";
            return;
        }


        emp user =loginClService.Findemp(empno);
        if(empname != "NULL")
            user.setEname(empname);
        if(empjob != "NULL")
            user.setJob(empjob);
        Integer empMgrr;
        if(empmgr.equals("NULL")){
            empMgrr = null;
            user.setMgr(empMgrr);
        }
        else
            user.setMgr(Integer.parseInt( empmgr ));


        if(empdate.equals("NULL")){
            System.out.println("data null");
        }
        else {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(empdate, df);
            user.setHiredate(date);
        }

        if(empsal.equals("NULL")){
            System.out.print("sal null");
        }
        else {
            BigDecimal bd0=new BigDecimal(empsal);
            user.setSal(bd0);
        }

        if(empcomm.equals("NULL")){
            System.out.print("comm null");
        }
        else {
            BigDecimal bd1=new BigDecimal(empcomm);
            user.setComm(bd1);
        }

        if(empdeptno.equals("NULL")) {
            System.out.print("deptno null");
        }
        else{
            user.setDeptno(Integer.parseInt( empdeptno ));
        }


        boolean upd = loginClService.serChaEmp(user);
        if (upd)
            flag_update = "OK";
        else
            flag_update = "NO";
        System.out.println("Control insert end!!!");
    }
    //更新是否成功，发到前端
    @RequestMapping("/SQLupdateflag")
    @ResponseBody
    public void updfalg(HttpServletRequest request, HttpServletResponse resp)  throws SQLException, ClassNotFoundException, IOException{
        PrintWriter out=resp.getWriter();
        out.println(flag_update);
        out.close();
    }


    @RequestMapping(value = "Cdata", method= RequestMethod.POST)
    public String dd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, IOException {
        System.out.println("00000000");
        req.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-type","text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        PrintWriter out=resp.getWriter();
        String json = "111111111";
        out.println(json);
        out.close();
        return json;
    }


    //前端向后端传数据
    @RequestMapping(value = "/ewer")
    @ResponseBody
    public void dataTran(HttpServletRequest request, HttpServletResponse response) throws SQLException, ClassNotFoundException,ServletException, IOException {
        System.out.println(loginClService.GetAllInfo(pages,count).size());
        //System.out.println(loginClService.GetAllInfo(pages,count));

        Iterator<Together> it = loginClService.GetAllInfo(pages,count).iterator() ;
        while(it.hasNext()) {
            Together str = it.next() ;
            /*if(str.equals("javaweb")) {
                it.remove();//此处删除集合中的一个元素
            }*/
            System.out.println(str.getEname());
        }

    }

    @RequestMapping(value = "/que")
    @ResponseBody
    public void dataTra(HttpServletRequest request, HttpServletResponse response) throws SQLException, ClassNotFoundException,ServletException, IOException {

        List test2 = new ArrayList();
        dept user1 = new dept();
        dept user2 = new dept();

        user1.setDeptno(111);
        user1.setDname("First Dept");
        user1.setLoc("AAA");

        user2.setDeptno(222);
        user2.setDname("Second Dept");
        user2.setLoc("BBB");



        test2.add(user1);
        test2.add(user2);
        JSONArray test = JSONArray.fromObject(test2);//此处的test是jsonObject的对象
        response.getWriter().println(test.toString());

    }

    @RequestMapping(value = "/INFOA")
    @ResponseBody
    public void dataA(HttpServletRequest request, HttpServletResponse response) throws SQLException, ClassNotFoundException,ServletException, IOException{
        List test2 = new ArrayList();
        Together page = new Together();
        page.setEmpno(pages/5+1);
        Collection<Together> user = loginClService.GetAllInfo(pages,count);
        Iterator<Together> it = user.iterator() ;
        while(it.hasNext()) {
            Together str = it.next() ;
            test2.add(str);
        }

        JSONArray test = JSONArray.fromObject(test2);//此处的test是jsonObject的对象
        response.getWriter().println(test.toString());
    }

    @RequestMapping(value = "/getPAGES")
    @ResponseBody
    public void getPages(HttpServletRequest request, HttpServletResponse response) throws SQLException, ClassNotFoundException,ServletException, IOException{
        Collection<Together> user = loginClService.GetAllInfo(-1,1);
        Allcount = user.size();
        if (Allcount%count == 0)
            response.getWriter().println(Allcount/count);
        else
            response.getWriter().println(Allcount/count+1);
    }

    @RequestMapping(value = "/getPaging")
    @ResponseBody
    public void getPaging(HttpServletRequest request, HttpServletResponse response) throws SQLException, ClassNotFoundException,ServletException, IOException{
        int pp = pages/5+1;
        System.out.println("当前号码："+pp);
        response.getWriter().println(pp);
    }

}

